﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace Cocon90.Lib.Util
{
    class WebClientEx
    {
        /// <summary>
        /// 创建WebClientEx新实例 
        /// </summary>
        /// <returns></returns>
        public static WebClientEx CreateInstence()
        {
            return new WebClientEx(new WebClient());
        }
        WebClientEx(WebClient wc) { this.WebClient = wc; }
        public WebClient WebClient { get; set; }
        /// <summary>
        /// 开始向此URL发请求（自动将使用异常读取的方式），请求完成后调用readComplted（2参数）委托
        /// </summary>
        /// <param name="url"></param>
        /// <param name="readComplted"></param>
        public void OpenRead(string url, OpenReadCompletedEventHandler readComplted)
        {
            if (WebClient == null) return;
            WebClient.OpenReadCompleted += readComplted;
            WebClient.OpenReadAsync(new Uri(url));
        }
        /// <summary>
        /// 异步上传文件到到指定的Url页面。其中filePath为本地文件全路径，uploadFinish表示发送成功时执行的委托
        /// </summary>
        public void PostFile(string filePath, string url, UploadFileCompletedEventHandler uploadFinish)
        {
            if (WebClient == null) return;
            WebClient.QueryString.Add("date", DateTime.Now.Millisecond + "");
            if (uploadFinish != null)
                WebClient.UploadFileCompleted += uploadFinish;
            WebClient.UploadFileAsync(new Uri(url), filePath);
        }
    }
}
